package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DeleteFileWithFileVisitor {
	public static void main(String[] args) throws IOException {
		Path directory = Paths.get("E:/Copy");
		DeleteDirectoryWithFileVisitor walk = new DeleteDirectoryWithFileVisitor();
		EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
		Files.walkFileTree(directory, opts, Integer.MAX_VALUE, walk);
	}
}

class DeleteDirectoryWithFileVisitor implements FileVisitor<Object> {

	boolean deleteFileByFile(Path file) throws IOException {
		return Files.deleteIfExists(file);
	}

	@Override
	public FileVisitResult postVisitDirectory(Object dir, IOException exc)
			throws IOException {

		if (exc == null) {
			System.out.println("访问: " + dir);

			boolean success = deleteFileByFile((Path) dir);

			if (success) {
				System.out.println("删除: " + dir);
			} else {
				System.out.println("未删除: " + dir);
			}
		} else {
			throw exc;
		}
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) {
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
		boolean success = deleteFileByFile((Path) file);
		if (success) {
			System.out.println("删除: " + (Path) file);
		} else {
			System.out.println("未删除: " + (Path) file);
		}
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(Object file, IOException exc) {
		return FileVisitResult.CONTINUE;
	}
}


